/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MapBottomTopicAdapter;
import com.srwl.mytx.adapter.SearchHistoryAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.SearchDataItem;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.fragment.GaoDeMapFragment;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.SearchView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.JzvdStd;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class TopicSearchActivity extends BaseActivity {
    private static final String TAG = "TopicSearchActivity";
    private SearchView searchView;
    private RecyclerView rv_searchHistory;
    private RecyclerView rv_searchResult;
    //private HomePageTopicAdapter topicAdapter;
    private MapBottomTopicAdapter topicAdapter;
    private SearchHistoryAdapter searchHistoryAdapter;
    private List<Topic> searchResultList = new ArrayList<>();
    private List<String> searchHistoryList = new ArrayList<>();
    private List<String> searchHotspotList = new ArrayList<>();     //热搜数据的集合
    private List<SearchDataItem> searchSumList = new ArrayList<>();     //搜索历史和热搜数据的集合
    private boolean showSearchResult;
    public int searchSumStringLength;
    private String hintString = "";  //搜索输入框的提示内容
    private ProgressBar progressBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private boolean hasNextPage;
    private int from = 0;
    private int size = 10;
    private String etContent;   //记录输入框中的数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        rv_searchHistory = findViewById(R.id.rv_search_history);
        rv_searchResult = findViewById(R.id.rv_search_result);
        progressBar = findViewById(R.id.progress_bar);
        refreshLayout = findViewById(R.id.refresh_layout);
        initSearchView();
        initSearchHistoryListView();
        findHotspotDataTopic();      //网络请求，获取后端的热搜数据
        initSearchResultListView();
        initRefreshLayout();
    }

    private void initSearchResultListView() {
        topicAdapter = new MapBottomTopicAdapter(this, searchResultList);
        rv_searchResult.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rv_searchResult.setAdapter(topicAdapter);
        topicAdapter.setCallbackToOutside(new MapBottomTopicAdapter.CallbackToOutside() {
            @Override
            public void jumpPage(Topic topic) {
                startActivityForResult(new Intent(TopicSearchActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL);
            }

            @Override
            public void commentJumpPage(Topic topic) {
                startActivityForResult(new Intent(TopicSearchActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic)
                        .putExtra(Constant.EXTRA_INFO_MESSAGE, "comment"), GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL);
            }
        });
    }


    private void initSearchView() {
        searchView = findViewById(R.id.search_view);
        searchView.setListener(new SearchView.InteractionListener() {
            @Override
            public void onSearch(String content) {
                //点击搜索，先判断其网络是否正常，以免造成，在无网环境下点击搜索崩溃
                if (!Helper.getInstance().isNetworkConnected()){
                    showToast_v1(getString(R.string.network_anomalies));
                    return;
                }
                //判断搜索输入框中是否输入了数据
                if (content.length() == 0) {
                    content = hintString;
                    searchView.et_content.setText(content);
                }
                from = 0; //每次搜索新数据之前from需要重置
                //搜索数据
                search(content,false);

                //把查询内容添加进搜索历史
                if (!searchHistoryList.contains(content)) {
                    if (searchHistoryList.size() == 0) {
                        searchSumList.add(0, new SearchDataItem("最近搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY));
                        searchHistoryList.add(content);
                    } else {
                        searchHistoryList.add(0, content);
                    }
                    searchSumList.add(1, new SearchDataItem(content, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                } else {
                    //删除已有的重复搜索记录，并将该条搜索记录重新添加到第一个搜索历史位置
                    int repeatElementIndex = searchHistoryList.indexOf(content);    //获取重复搜索元素的索引
                    searchHistoryList.remove(content);
                    searchSumList.remove(repeatElementIndex + 1);
                    searchHistoryList.add(0, content);
                    searchSumList.add(1, new SearchDataItem(content, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                }
                //判断搜索记录是否为11条，如果为11条就删除最后一条，使其只保存10条
                if (searchHistoryList.size() == 11) {
                    searchHistoryList.remove(10);
                    searchSumList.remove(11);
                }
                PreferenceManager.getInstance().setCurrentUserSearchHistoryTopic(searchHistoryList);
                searchHistoryAdapter.notifyDataSetChanged();
            }

            @Override
            public void onTextChange(String content) {
                //当输入框内容改变时回调
                if (content.length() == 0) {
                    searchResultList.clear();
                    topicAdapter.notifyDataSetChanged();
                    //当输入框内容为空时，让"历史搜索记录"显示出来
                    refreshLayout.setVisibility(View.GONE);
                    rv_searchHistory.setVisibility(View.VISIBLE);

                }
            }
        });

//
//        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    showSearchHistory();
//                    rv_searchHistory.setVisibility(View.VISIBLE);
//                } else {
//                    rv_searchHistory.setVisibility(View.GONE);
//
//                }
//
//            }
//        });


//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                //把查询内容添加进搜索历史
//                if (!searchHistoryList.contains(query)) {
//                    searchHistoryList.add(0, query);
//                    PreferenceManager.getInstance().setCurrentUserSearchHistoryTopic(searchHistoryList);
//                    searchHistoryAdapter.notifyDataSetChanged();
//                }
//                search(query, null);
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                //如果输入框没有内容，显示搜索历史
//                if (newText == null || newText.equals("")) {
//                    showSearchHistory();
//                }
//                //做搜索建议
//                return false;
//            }
//        });

        //滑动删除
        /*ItemTouchHelper touchHelper = new ItemTouchHelper(new MyItemTouchHelperCallBack());
        touchHelper.attachToRecyclerView(rv_searchHistory);*/
    }

    void initRefreshLayout() {
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setOnRefreshListener(new MaterialSmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    search(etContent,true);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }


    /*
    从服务端获取热搜数据
     */
    public void findHotspotDataTopic() {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }

        //发起网络请求，从服务器获取热搜数据
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .hotspotData()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult commonResult = response.body();

                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "onResponse: 响应失败！" + response.message());
                            return;
                        }
                        if (commonResult.isError()) {
                            Log.e(TAG, "onResponse: 响应错误！" + commonResult.getMsg());
                            return;
                        }
                        Log.d(TAG, "响应回来的热搜数据是: " + commonResult);

                        JSONArray jsonArray = (JSONArray) commonResult.getData();
                        //将服务器端响应回的热搜数据添加到热搜集合中
                        searchHotspotList.addAll(jsonArray.toJavaList(String.class));

                        if (searchHistoryList.size() != 0) {
                            searchSumList.add(new SearchDataItem("最近搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY));
                            for (String searchHistory : searchHistoryList) {
                                searchSumList.add(new SearchDataItem(searchHistory, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                            }
                        }

                        if (searchHotspotList.size() != 0) {
                            searchSumList.add(new SearchDataItem("热门搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HOTSPOT));
                            for (String s : searchHotspotList) {
                                searchSumList.add(new SearchDataItem(s, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_REMOTE_CONTENT));
                            }
                        }
                        searchHistoryAdapter.notifyDataSetChanged();

                        //从热搜数据集合中随机获取一条设置为输入框的Hint
                        if (searchHotspotList.size() != 0) {
                            int randomIndex = (int) (Math.random() * (searchHotspotList.size() - 1));
                            hintString = searchHotspotList.get(randomIndex);
                            searchView.et_content.setHint(hintString);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        t.printStackTrace();
                    }
                });
    }

    private void search(String query,Boolean whetherLoadMore ) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (whetherLoadMore) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        hideSoftKeyboard();
        if (rv_searchHistory.getVisibility() != View.GONE)
            rv_searchHistory.setVisibility(View.GONE);
        if (!whetherLoadMore){
            //上拉加载的情况不显示progressBar
            progressBar.setVisibility(View.VISIBLE);
        }
        etContent = query;
        Map<String, Object> info = new HashMap<>();
        info.put("queryContent", query);
        info.put("from", from);
        info.put("size", size);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .search(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES搜索失败：" + result.getMsg());
                            return;
                        }
                        if (!whetherLoadMore){
                            //非上拉加载情况清空
                            searchResultList.clear();
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        Integer total = jsonObject.getJSONObject("total").getInteger("value");

                        if (resultsList.size() == 0) {
                            topicAdapter.showNoDataView();
                        } else {
                            searchResultList.addAll(resultsList);
                            topicAdapter.showNormalView(from, size);
                            //topicAdapter.showNormalView();
                        }
                        hasNextPage = from + size < total;
                        if (hasNextPage) {
                            from = from + size;
                            if (!(refreshLayout.getFooterView() instanceof MaterialFooter))
                                refreshLayout.setFooterView(new MaterialFooter(TopicSearchActivity.this));
                        } else {
                            if (!(refreshLayout.getFooterView() instanceof NodataFooter)) {
                                refreshLayout.postDelayed(() -> {
                                    refreshLayout.setFooterView(new NodataFooter(TopicSearchActivity.this));
                                }, 1000);
                            }
                        }

                        //搜索完成后，隐藏历史记录的RecyclerView，显示搜索的RecyclerView
                        if (refreshLayout.getVisibility() != View.VISIBLE) {
                            refreshLayout.setVisibility(View.VISIBLE);
                        }
                        refreshLayout.refreshComplete();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        topicAdapter.showErrorView();
                        Log.e(TAG, "ES搜索失败：" + t.getMessage());

                    }
                });
    }


    private void initSearchHistoryListView() {
        List<String> currentUserSearchHistory = PreferenceManager.getInstance().getCurrentUserSearchHistoryTopic();

        if (currentUserSearchHistory != null) {
            searchHistoryList.addAll(currentUserSearchHistory);
            Log.d(TAG, "本地搜索历史数据: " + currentUserSearchHistory);
        }

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 840);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                //获取每一个历史搜索和热搜的字符串长度
                searchSumStringLength = searchSumList.get(position).getContent().length();
                if (searchSumList.get(position).getType() == SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY
                        || searchSumList.get(position).getType() == SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HOTSPOT) {
                    //当item类型为title时，使其item独占一行
                    return 840;
                } else if (searchSumStringLength == 1) {
                    return 840 / 8;
                } else if (searchSumStringLength == 2) {
                    return 840 / 6;
                } else if (searchSumStringLength == 3) {
                    return 840 / 4;
                } else if (searchSumStringLength == 4) {
                    return 840 / 4;
                } else if (searchSumStringLength == 5) {
                    return 840 / 3;
                } else if (searchSumStringLength == 6) {
                    return 840 / 3;
                } else if (searchSumStringLength == 7) {
                    return 840 / 2;
                } else if (searchSumStringLength >= 8) {
                    return 840 / 2;
                }
                return 0;
            }
        });

        rv_searchHistory.setLayoutManager(gridLayoutManager);
        searchHistoryAdapter = new SearchHistoryAdapter(this, searchSumList);
        rv_searchHistory.setAdapter(searchHistoryAdapter);

        searchHistoryAdapter.setSearchHistoryItemClickListener(new SearchHistoryAdapter.SearchHistoryItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String content = searchSumList.get(position).getContent();
                searchView.et_content.setText(content);
                from = 0;   //重新搜索数据之前，from需要重新开始
                search(content,false);
            }

            @Override
            public void onItemLongClick(int position) {

                ConfirmDialog dialog = new ConfirmDialog(TopicSearchActivity.this, "提醒", "确定删除吗？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        String remove = searchSumList.remove(position).getContent();
                        searchHistoryList.remove(remove);
                        if (searchHistoryList.size() == 0) {
                            //如果搜索历史的内容为0，则在适配器数据源中移除"搜索历史:"标题栏
                            searchSumList.remove(0);
                        }
                        searchHistoryAdapter.notifyDataSetChanged();
                        PreferenceManager.getInstance().setCurrentUserSearchHistoryTopic(searchHistoryList);
                    }
                });

                dialog.show();

            }

        });

        searchHistoryAdapter.setSearchHistoryClearAll(new SearchHistoryAdapter.SearchHistoryClearAll() {
            @Override
            public void clearAll(int position) {
                //点击清除所有搜索历史的图标后的回调执行逻辑
                ConfirmDialog dialog = new ConfirmDialog(TopicSearchActivity.this, "提醒", "确认清除所有历史记录吗？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        //删除所有历史搜索数据
                        int size = searchHistoryList.size();
                        searchHistoryList.clear();
                        PreferenceManager.getInstance().setCurrentUserSearchHistoryTopic(searchHistoryList);
                        for (int i = 0; i <= size; i++) {
                            searchSumList.remove(0);
                        }
                        searchHistoryAdapter.notifyDataSetChanged();
                    }
                });
                dialog.show();

            }
        });

    }

    public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (showSearchResult) {
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            if (viewHolder.getAdapterPosition() == searchHistoryAdapter.getItemCount() - 1) {
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Log.d(TAG, "onSwiped: 滑动删除，，，，");
            //searchHistoryAdapter.removeSearchHistory(viewHolder.getAdapterPosition());
            // TODO: 2019-10-07
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//            Intent backHome = new Intent(Intent.ACTION_MAIN);
//            backHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            backHome.addCategory(Intent.CATEGORY_HOME);
//            startActivity(backHome);
//            return true;
//        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (updateTopic == null) {
            return;
        }

        for (int i = 0; i < searchResultList.size(); i++) {
            Topic topic = searchResultList.get(i);
            if (TextUtils.equals(topic.getId(), updateTopic.getId())) {
                //处理当前topic，是删除、下架、或是改变数据
                if (data.getBooleanExtra(Constant.EXTRA_TOPIC_DELETE, false) || data.getBooleanExtra(Constant.EXTRA_TOPIC_BACK_OUT, false)) {
                    searchResultList.remove(i);
                    topicAdapter.notifyItemChanged(i);
                } else if (data.getBooleanExtra(Constant.EXTRA_TOPIC_CHANGE, false)) {
                    //topic中数据改变
                    searchResultList.remove(i);
                    searchResultList.add(i, updateTopic);
                    topicAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JzvdStd.resetAllVideos();
    }
}
